package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetize.plus.entity.po.CommentDislike;
import com.poetize.plus.entity.po.CommentLike;
import com.poetize.plus.mapper.CommentDislikeMapper;
import com.poetize.plus.mapper.CommentLikeMapper;
import com.poetize.plus.service.CommentDislikeService;
import com.poetize.plus.utils.LoginUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author zuosy
 * @created 2024/4/11 16:46
 */
@Service
@RequiredArgsConstructor
public class CommentDislikeServiceImpl extends ServiceImpl<CommentDislikeMapper, CommentDislike> implements CommentDislikeService {

    private final CommentLikeMapper commentLikeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean dislike(Long commentId) {
        String userName = LoginUtils.getLoginUserName();

        CommentDislike dislike = lambdaQuery()
                .eq(CommentDislike::getCommentId, commentId)
                .eq(CommentDislike::getCreateBy, userName)
                .one();

        /*
         * 1：如果还没点赞就增加点赞，如果同时存在对该评论的点踩操作，则会取消点踩；
         * 2：如果已经点赞，则取消点赞；
         * */
        return Optional.ofNullable(dislike)
                .map(dis -> baseMapper.deleteById(dis) > 0)
                .orElseGet(() -> {
                    CommentDislike commentDislike = new CommentDislike();
                    commentDislike.setCommentId(commentId);
                    baseMapper.insert(commentDislike);

                    commentLikeMapper.delete(new LambdaQueryWrapper<CommentLike>()
                            .eq(CommentLike::getCommentId, commentId)
                            .eq(CommentLike::getCreateBy, userName));
                    return true;
                });
    }
}
